package com.gitee.sop.layui.adminserver.plugins.shiro;

import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author: huwei
 * @date: 2020/7/10 9:08
 * @version: 1.0.0
 */
public class ShiroMobileSessionManager extends DefaultWebSessionManager {

    private static final String CUSTOM_SESSION_ID_KEY = "X-S-AUTH-TOKEN";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        //请求头
        Serializable sessionId = req.getHeader(CUSTOM_SESSION_ID_KEY);
        //为空，从请求体获取
        if (Objects.isNull(sessionId)) {
            sessionId = request.getParameter(CUSTOM_SESSION_ID_KEY);
        }
        //cookie
        if (Objects.isNull(sessionId)) {
            Cookie[] cookies = req.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (int i = 0; i < cookies.length; ++i) {
                    if (cookies[i].getName().equals("JSESSIONID")) {
                        sessionId = cookies[i].getValue();
                        break;
                    }
                }
            }
        }
        if (Objects.isNull(sessionId)) {
            sessionId = super.getSessionId(request, response);
        }
        return sessionId;
    }
}
